//用react封装
var currentpage = 1,totlepage = 1,i,phoneState = true;//分页的当前页和总的页数 手机号码格式是否正确
//表单数据：设备IMEI号、家长姓名、手机号、身份证号、地址、手机型号、手机系统版本
var tableData = [];
//表单的最高高度、当前第几页、总页数、总行数
var otherData = {maxHeight:'0px',pageLeft:0,pageRight:0};
//分页
var Page = React.createClass({
    setPage: function (e) {
        setPage($(e.target).html());
        this.props.onPageClick(1);
    },
    showPage: function () {
        showPage();
    },
    render: function () {
        {
            var items = [],
                svar = this;
            if(totlepage == 0 ){
                items.push({num:1,checked:true})
            }else if(totlepage < 6){
                for(i = 1;i <= totlepage ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage >= (totlepage-2)) {//点在左边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                for(i = totlepage-2;i <= totlepage ;i++){
                    if(i == currentpage){
                        items.push({num:i,checked:true})
                    }else{
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage <= 3){
                for(i = 1;i <= 3 ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
                items.push({num:'···',checked:false});
                items.push({num:totlepage,checked:false})
            }else {//点在两边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:currentpage-1,checked:false});
                items.push({num:currentpage,checked:true});
                items.push({num:currentpage+1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:totlepage,checked:false})
            }
        }
        return (
            <div className="tableInfo-page">
                <div className="page-number">每页<span className="page-number-list" onClick={this.showPage}>{pagecount}</span>条</div>
                <div className="page-list" style={{top:pageListTop+"px"}}>
                    <ul>
                        {
                            pageList.map(function (item) {
                                return (<li onClick={svar.setPage}>{item}</li>)
                            })
                        }
                    </ul>
                </div>
                <div className="page-limit">
                    <ol className="page-limit-ol">
                        <li className="page-limit-img" name="-1" onClick={otherData.pageLeft == 0?'':svar.props.onPageClick.bind(svar,-1)}><span className={otherData.pageLeft == 0?'page-limit-left-no':'page-limit-left-yes'}/></li>
                        {
                            items.map(function (item) {
                                return (<li onClick={isNaN(item.num)?'':svar.props.onPageClick.bind(svar,item.num)}  className={item.checked == true?'page-limit-num page-limit-checked':'page-limit-num'} name={item.num}>{item.num}</li>)
                            })
                        }
                        <li className="page-limit-img" name="-2" onClick={otherData.pageRight == 0?'':svar.props.onPageClick.bind(svar,-2)}><span className={otherData.pageRight == 0?'page-limit-right-no':'page-limit-right-yes'}/></li>
                    </ol>
                </div>
            </div>
        );
    }
});
//表单组件
var Table = React.createClass({
    render: function () {
        return (
            <tr>
                <td style={{width: '7%'}}>{parseInt(this.props.listNumber)+1}</td>
                <td style={{width: '15%'}}>{this.props.mdtid}</td>
                <td style={{width: '10%'}}>{this.props.queryresultPeoplename}</td>
                <td style={{width: '13%'}}>{this.props.queryresultPeopletel}</td>
                <td style={{width: '15%'}}>{this.props.queryresultPeopleidcard}</td>
                <td style={{width: '20%'}}>{this.props.queryresultHomeaddr}</td>
                <td style={{width: '20%'}}><div className="trButton upPhone trLeft trLong" style={{width:"85px"}} onClick={this.props.onClickShowPop}>修改手机帐号</div>{localStorage.salesAuthority=="false"?'':<div className="trButton resetPwd trLeft trLong" onClick={this.props.onClickResetPwd}>重置密码</div>}</td>
            </tr>
        );
    }
});
//父组件
var Main = React.createClass({
    //组件初始状态
    getInitialState: function () {
        return {otherData:this.props.otherData,tableData:this.props.tableData}
    },
    componentDidMount: function () {
        //使用ajax取出数据然后组装数据列表
        var height = $(document.body).height()+"px";
        var svar = this;
        suixun.ajax(serverUrl+'/parentInfoManage/queryParentList.json?param={pagenumber:1,pagecount:"'+pagecount+'"}','',"get",function(data){
            setTimeout(function () {
                suixun.hideLoding();//隐藏加载中
            },200);
            if(data.code == 200){
                for(var i=0;i<data.info.queryresult.length;i++){
                    var obj=data.info.queryresult[i];
                    tableData[i] = {keyid:i,queryresultPeopleid:obj.peopleid,mdtid:obj.mdtid,queryresultPeoplename:obj.peoplename,queryresultPeopletel:obj.peopletel,queryresultPeopleidcard:obj.peopleidcard,queryresultHomeaddr:obj.homeaddr};
                }
                var pageRight = 0;
                if(data.info.totlepage > 1){
                    pageRight = 1
                }
                otherData = {maxHeight:height,pageLeft:0,pageRight:pageRight};
                currentpage = 1;totlepage = data.info.totlepage;//初始化的时候赋值：分页的当前页和总的页数
                svar.setState({tableData:tableData,otherData:otherData});
            }
        });
        //绑定回车时间
        $(document).keypress(function(e) {
            var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
            if (eCode == 13){
                if($(".enterEvent").is(":focus")){
                    svar.onClickQuery();
                }
            }
        });
    },
    onClickQuery: function () {

        var queryType = $(".school-or-parent").html(),queryKey = "parentphone",inputValue = $(".queryVal").val();
        if(queryType == "姓名"){
            queryKey = "parentname";
        }else{
            if(!/^[1-9]\d*$/.test(inputValue) && inputValue != ""){
                suixun.alert("手机号格式不对！",function (data) {
                    if(data){
                        $(".queryVal").val("")
                    }
                });
                return;
            }
        }
        var param="param={";
        param = getJsonDataNotEmpty(param,""+queryKey+"",'"'+inputValue+'"');
        param = getJsonDataNotEmpty(param,"pagenumber",""+currentpage+"");
        param = getJsonDataNotEmpty(param,"pagecount",pagecount+'');
        param += "}";
        var height = $(document.body).height()+"px";
        var svar = this;
        suixun.showLoding();//显示加载中
        suixun.ajax(serverUrl+'/parentInfoManage/queryParentList.json?'+param,'',"get",function(data){
            tableData = [];
            suixun.hideLoding();//隐藏加载中
            if(data.code == 200){
                for(var i=0;i<data.info.queryresult.length;i++){
                    var obj=data.info.queryresult[i];
                    tableData[i] = {keyid:i,queryresultPeopleid:obj.peopleid,mdtid:obj.mdtid,queryresultPeoplename:obj.peoplename,queryresultPeopletel:obj.peopletel,queryresultPeopleidcard:obj.peopleidcard,queryresultHomeaddr:obj.homeaddr};
                }
                var pageRight = 0;
                if(data.info.totlepage > 1){
                    pageRight = 1
                }
                otherData = {maxHeight:height,pageLeft:0,pageRight:pageRight};
                totlepage = data.info.totlepage;//初始化的时候赋值：分页的当前页和总的页数
                svar.setState({tableData:tableData,otherData:otherData});
            }
        });
    },
    onPageClick: function (num) {
        //分页-调用ajac然后把数据查询出来:获取name的值
        //计算currentpage
        suixun.showLoding();//显示加载中
        var onPageLeft = 0,onPageRight = 1,savr = this;
        if(num > 0){
            currentpage = num;
        }else if(num == -1 && currentpage > 1){
            currentpage --;
        }else if(num == -2  && currentpage < totlepage){
            currentpage ++;
        }else{
            return;
        }
        //修改左右的按钮
        if((currentpage == totlepage && totlepage == 1)|| totlepage == 0){
            onPageLeft = 0;
            onPageRight = 0;
        }else if(currentpage == totlepage && totlepage > 1){
            onPageLeft = 1;
            onPageRight = 0;
        }else if(1 < currentpage && currentpage < totlepage){
            onPageLeft = 1;
            onPageRight = 1;
        }
        var queryType = $(".school-or-parent").html(),queryKey = "parentphone";
        if(queryType == "姓名"){
            queryKey = "parentname";
        }
        var param="param={";
        param = getJsonDataNotEmpty(param,""+queryKey+"",'"'+$(".queryVal").val()+'"');
        param = getJsonDataNotEmpty(param,"pagenumber",'"'+currentpage+'"');
        param = getJsonDataNotEmpty(param,"pagecount",pagecount+'');
        param += "}";
        var height = $(document.body).height()+"px";
        suixun.ajax(serverUrl+'/parentInfoManage/queryParentList.json',param,"get",function(data){
            tableData = [];
            suixun.hideLoding();//隐藏加载中
            if(data.code == 200){
                for(var i=0;i<data.info.queryresult.length;i++){
                    var obj=data.info.queryresult[i];
                    tableData[i] = {keyid:i,queryresultPeopleid:obj.peopleid,mdtid:obj.mdtid,queryresultPeoplename:obj.peoplename,queryresultPeopletel:obj.peopletel,queryresultPeopleidcard:obj.peopleidcard,queryresultHomeaddr:obj.homeaddr};
                }
                if(data.info.totlepage > 1 && data.info.totlepage > currentpage){
                    onPageRight = 1
                }else{
                    onPageRight = 0;
                }
                otherData = {maxHeight:height,pageLeft:onPageLeft,pageRight:onPageRight};
                totlepage = data.info.totlepage;//初始化的时候赋值：分页的当前页和总的页数
                savr.setState({tableData:tableData,otherData:otherData});
            }
        });
    },
    //家长修改手机账号
    onClockUpPhone: function () {
        var phone = $('.phone-content').val();
        if(phone == ""){
            suixun.alert("家长手机号不能为空!");
            $(".errorMsg").show();
            return;
        }else if(phone.length != 11){
            suixun.alert("家长手机号格式错误!");
            $(".errorMsg").show();
            return;
        }else if(!/^[1-9]\d*$/.test(phone)){
            suixun.alert("家长手机号格式错误!");
            $(".errorMsg").show();
            return;
        }else{
            $(".errorMsg").hide();
        }

        var svar = this;
        if(phoneState){
            suixun.showLoding();//显示加载中
            var param = "param={parentphone:"+phone+",parentid:"+$('.popModel-body-phone-id').html()+"}";//mdtid:"+$('.popModel-body-imei-content').html()+",
            suixun.ajax(serverUrl+'/parentInfoManage/phoneService.json',param,"get",function(data){
                suixun.hideLoding();//隐藏加载中
                if(data.code == 200){
                    suixun.alert("修改成功!",function (data) {
                        if(data){
                            svar.onClickHidePop();//关闭窗口
                            svar.onPageClick(currentpage);//更新数据
                        }
                    });
                }else if(data.code == 500){
                    $(".errorMsg").show();
                    $('.phone-content').val("");
                    suixun.alert(data.msg);
                }
            });
        }
    },
    //显示修改手机号pop
    onClickShowPop: function (info) {
        //现在就把imei号传过来了   ps到时候把家长的id一起传过来
        $(".popModel-body-phone-id").html(info[0]);//家长id
        $(".phone-content").val(info[1]);//家长的phone
        $(".popModel-body-imei-content").html(info[2]);//IMEI号
        $(".popModel").show();

    },
    //关闭修改手机号pop
    onClickHidePop: function () {
        $(".popModel").hide();
        $(".errorMsg").hide();
    },
    //重置密码
    onClickResetPwd: function(info){
        suixun.confirm_noTit('是否重置密码?',function (data) {
            if(data == true){
                var param = "param={mdtid:"+info[2]+",parentphone:"+info[1]+",parentid:"+info[0]+"}";
                suixun.ajax(serverUrl+'/parentInfoManage/passwordService.json',param,"get",function(data){
                    if(data!=null && data.code == 200){
                        if(data.info.resultstatus == 1){
                            suixun.alert("重置密码成功!");//新密码：data.info.resultpassword
                        }else{
                            suixun.alert("重置密码失败");
                        }
                    } else {
                        suixun.alert("重置密码失败");
                    }
                });
            }
        });
    },
    //验证手机号码格式
    onChangePhone: function (e) {
        var val = e.target.value;
        if(val == ""){
            $(".errorMsg").show();
            phoneState = false;
            return false;
        }else if(val.length != 11){
            $(".errorMsg").show();
            phoneState = false;
            return false;
        }
        phoneState = true;
        $(".errorMsg").hide();
    },
    /**
     * 验证输入框的长度
     * @returns {XML}
     */
    onInputNumber:function (e) {
        var value = e.target.value;
        if(value.length > 11){
            $(e.target).val(value.slice(0,11));
        }
    },
    render: function () {
        {
            var svar = this;
            var onClickArray = [this.onClickShowPop,this.onClickResetPwd];
            var Tabels = this.state.tableData.map(function (data,index) {
                return (//svar.props.onPageClick.bind(svar,item.num) .bind(svar,data.mdtid)
                    <Table key={index} listNumber={index} onClickShowPop={onClickArray[0].bind(svar,[data.queryresultPeopleid,data.queryresultPeopletel,data.mdtid])} onClickResetPwd={onClickArray[1].bind(svar,[data.queryresultPeopleid,data.queryresultPeopletel,data.mdtid])} mdtid={data.mdtid} queryresultPeoplename={data.queryresultPeoplename} queryresultPeopletel={data.queryresultPeopletel} queryresultPeopleidcard={data.queryresultPeopleidcard} queryresultHomeaddr={data.queryresultHomeaddr}  />
                )
            })
        }
        return (
            <div className="tableManage-body">
                <div  className="popPhone popModel">
                    <div className="model"></div>
                    <div className="popModel-info">
                        <div className="popModel-title">
                            <span className="popModel-title-content">
                                <span className="popModel-title-content-solid-left"/>
                                    修改手机账号
                                <span className="popModel-title-content-solid-right"/>
                            </span>
                            <span className="popModel-title-img" onClick={this.onClickHidePop}><img src="../img/icon/close.png" alt="关闭"/></span>
                        </div>
                        <div className="popModel-body">
                            <div className="popModel-body-imei">
                                <span className="popModel-body-imei-title">设备IMEi号</span>
                                <span className="popModel-body-imei-content"/>
                            </div>
                            <div className="popModel-body-phone popModel-body-input">
                                <span className="popModel-body-phone-title popModel-body-input-title">家长手机号</span>
                                <span className="popModel-body-phone-id popModel-body-input-id" style={{display:'none'}}/>
                                <span className="popModel-body-phone-content popModel-body-input-content">
                                    <input className="phone-content input-content " type="text" onInput={this.onInputNumber} placeholder="请输入要修改的手机号码" onChange={this.onChangePhone} />
                                </span>
                                <div className="errorMsg" ></div>
                            </div>
                        </div>
                        <div className="popModel-button">
                            <span className="popModel-button-ok" onClick={this.onClockUpPhone}>确定</span>
                        </div>
                    </div>
                </div>
                <header>
                    <div className="header-left">
                        {
                            localStorage.salesAuthority=="false"?
                                <div className="header-left-studentInfo">
                                    <a href="../parentInfoManage/queryParentList.html" className="header-left-button showOrder">家长管理</a>
                                </div>
                                :
                                <div className="header-left-studentInfo">
                                    <a href="../parentInfoManage/queryParentList.html" className="header-left-button showOrder">家长管理</a>
                                    <a href="../teacherManage/classTeacher.html" className="header-left-button" style={{left:"10px"}}>教师管理</a>
                                    <a href="../studentInfoManage/queryStduentList.html"  className="header-left-button " style={{left:"20px"}}>学生管理</a>
                                </div>
                        }
                        {/*<div className="header-left-studentInfo">*/}
                            {/*<a href="../parentInfoManage/queryParentList.html" className="header-left-button showOrder">家长管理</a>*/}
                            {/*<a href="../teacherManage/classTeacher.html" className="header-left-button" style={{left:"10px"}}>教师管理</a>*/}
                            {/*<a href="../studentInfoManage/queryStduentList.html"  className="header-left-button " style={{left:"20px"}}>学生管理</a>*/}
                        {/*</div>*/}
                        <div className="header-left-annotationsInfo">
                            <img src="../img/icon/annotations.png" />
                            <span className="header-left-annotations-arrowsLeft"/>
                            <div className="header-left-annotations">这里是注释。</div>
                        </div>
                    </div>
                    <div className="header-right">
                        <div className="header-right-select droup-select">
                            <div className="school-or-parent school-or-table" >手机号</div>
                            <span className="lower-right-corner"/>
                            <div className="drop-down" >
                                <span className="select-value school-name" >手机号</span>
                                <span className="select-value parent-name" >姓名</span>
                            </div>
                        </div>
                        <div className="header-right-query">
                            <div className="header-right-query-input">
                                <input className="queryVal enterEvent" type="text" maxLength="11" placeholder="请输入家长手机号搜索"/>
                            </div>
                            <div className="header-right-query-img" onClick={this.onClickQuery}></div>
                        </div>
                    </div>
                </header>
                <div className="parentsInfo tableInfo">
                    <div className="parentsInfo-data tableInfo-data">
                        <div className="parentsInfo-data-table tableInfo-data-table" >
                            <table className="head-body head-body">
                                <thead>
                                    <th style={{width: '7%'}}>序号</th>
                                    <th style={{width: '15%'}}>设备IMEI号</th>
                                    <th style={{width: '10%'}}>家长姓名</th>
                                    <th style={{width: '13%'}}>手机帐号</th>
                                    <th style={{width: '15%'}}>身份证号</th>
                                    <th style={{width: '20%'}}>地址</th>
                                    <th style={{width: '20%'}}>操作</th>
                                </thead>
                                <tbody>
                                    {this.state.tableData==""?'':Tabels}
                                </tbody>
                            </table>
                            {this.state.tableData==""?<div className="tableNoData">{tableNoDataCount}</div>:''}
                        </div>
                    </div>
                    <Page otherData={this.state.otherData} onPageClick={this.onPageClick} />
                </div>
                <footer id="copyright">
                    <span><img src="../img/icon/copyright.png"/>{copyright}</span>
                </footer>
            </div>
        );
    }
});
ReactDOM.render(
    <Main  otherData={otherData} tableData={tableData} />,
    document.getElementById('tableManage')
);
/* $(function () {
 $(".parentsInfo-data-table").css("maxHeight",$(document.body).height()-260+"px");//直接先计算然后在虚拟dom中设置
 });*/
//点击下拉框
$(".header-right-select").click(function () {
    var dropDown = $(this).find('.drop-down');
    if(dropDown.is(":hidden")){
        dropDown.slideDown();
    }else{
        dropDown.slideUp();
    }
});
// //鼠标移动函数 —— 下拉选择手机号、姓名
// $('.header-right .school-or-parent').hover(function(){
//         if($(".drop-down").is(":hidden")){
//             $(this).parent().find('.drop-down').slideDown();
//             $(this).parent().hover(function(){},
//                 function(){
//                     $(this).parent().find(".drop-down").slideUp();
//                 }
//             );
//         }
//     },function(){}
// );
//选择手机号、姓名
$('.drop-down>span').click(function() {
    $(".queryVal").attr("placeholder","请输入家长"+$(this).html()+"搜索");
    if($(this).html()=="手机号" && $(".school-or-parent").html() != "手机号"){
        $(".queryVal").val("").attr("maxLength","11");
    }else if($(this).html()=="姓名" && $(".school-or-parent").html() != "姓名"){
        $(".queryVal").val("").attr("maxLength","20");
    }
    $(".school-or-parent").html($(this).html());
    $('.drop-down').slideUp();
});